package com.jiadeyu.utils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ThreadLocalUtil {
    // 使用 ConcurrentHashMap 来确保线程安全
    private static final Map<String, ThreadLocal<?>> THREAD_LOCAL_MAP = new ConcurrentHashMap<>();

    // 用于存储和获取 ThreadLocal 的方法
    private static <T> ThreadLocal<T> createThreadLocal(String name) {
        // 检查是否已经存在相同名称的 ThreadLocal
        if (THREAD_LOCAL_MAP.containsKey(name)) {
            return (ThreadLocal<T>) THREAD_LOCAL_MAP.get(name);
        }

        // 创建一个新的 ThreadLocal 并将其存储在 map 中
        ThreadLocal<T> threadLocal = new ThreadLocal<>();
        THREAD_LOCAL_MAP.put(name, threadLocal);
        return threadLocal;
    }

    // 获取已经创建的 ThreadLocal（如果存在）
    private static <T> ThreadLocal<T> getThreadLocal(String name) {
        return (ThreadLocal<T>) THREAD_LOCAL_MAP.get(name);
    }

    public static void set(String name, Object value) {
        ThreadLocal<Object> threadLocal = ThreadLocalUtil.createThreadLocal(name);
        threadLocal.set(value);
    }
    public static <T> T get(String name) {
        ThreadLocal<Object> threadLocal = ThreadLocalUtil.createThreadLocal(name);
        return (T) threadLocal.get();
    }

    public static void remove(String name) {
        ThreadLocal<Object> threadLocal = ThreadLocalUtil.createThreadLocal(name);
        threadLocal.remove();
    }
}

